import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { White } from 'style/Color';
import { URL } from 'service/URLService';
import Image from 'widget/Image';

const ts = URL.search('ts') || '';
const searchs = ts ? `?ts=${ts}` : '';

const AvatarRoot = styled.div`
  width: 100%;
  height: 100%;
  background-color: ${White};
`;

class Avatar extends Component {
  constructor(props) {
    super(props);
    const { data } = props;
    const { id } = data;
    this.state = {
      opacity: 0,
      link: URL.profile(id),
      avatar: URL.avatar(id) + searchs
    };
    this.fadeIn = this.fadeIn.bind(this);
    this.useDefault = () => {
      this.setState({
        avatar: URL.avatar('default')
      });
    };
  }

  fadeIn() {
    const opacity = 1;
    this.setState({ opacity });
  }

  render() {
    const { asLink } = this.props;
    const { link, avatar } = this.state;

    const image = (
      <Image
        style={{ borderRadius: '50%', overflow: 'hidden' }}
        onError={this.useDefault}
        src={avatar}
      />
    );
    return <AvatarRoot>{asLink ? <a href={link}>{image}</a> : image}</AvatarRoot>;
  }
}

Avatar.defaultProps = {
  asLink: true
};

Avatar.propTypes = {
  data: PropTypes.shape({
    id: PropTypes.number.isRequired
  }).isRequired,
  asLink: PropTypes.bool
};

export default Avatar;
